package com.chiao.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * @author zhangyinyou
 * 
 */
public class CommonUtils {

	/**
	 * StringUtils.isEmpty(null) = true StringUtils.isEmpty("") = true
	 * StringUtils.isEmpty(" ") = false
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return StringUtils.isEmpty(str);
	}

	/**
	 * StringUtils.isBlank(null) = true StringUtils.isBlank("") = true
	 * StringUtils.isBlank(" ") = true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		return StringUtils.isBlank(str);
	}

	public static String join(Iterable<?> iterable, String separator) {
		return StringUtils.join(iterable, separator);
	}

	public static String join(Object[] array, String separator) {
		return StringUtils.join(array, separator);
	}

	/**
	 * 从左边开始截取字符串
	 * 
	 * @param str
	 * @param len
	 * @return
	 */
	public static String subLeft(String str, int len) {
		return StringUtils.left(str, len);
	}

	/**
	 * 从右边开始截取字符串
	 * 
	 * @param str
	 * @param len
	 * @return
	 */
	public static String subRight(String str, int len) {
		return StringUtils.right(str, len);
	}

	/**
	 * 生成随机字符串
	 * 
	 * @param count
	 * @return
	 */
	public static String randStr(int count) {
		return RandomStringUtils.random(count);
	}


	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		return NumberUtils.isNumber(str);
	}

	/**
	 * 字符串转double
	 * 
	 * @param str
	 * @return
	 */
	public static double toDouble(String str) {
		return NumberUtils.toDouble(str);
	}

	/**
	 * 字符串转float
	 * 
	 * @param str
	 * @return
	 */
	public static float toFloat(String str) {
		return NumberUtils.toFloat(str);
	}

	/**
	 * 字符串转int
	 * 
	 * @param str
	 * @return
	 */
	public static int toInt(String str) {
		return NumberUtils.toInt(str);
	}

	/**
	 * 字符串转long
	 * 
	 * @param str
	 * @return
	 */
	public static long toLong(String str) {
		return NumberUtils.toLong(str);
	}

	/**
	 * 格式化日期
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(Date date, String pattern) {
		return DateFormatUtils.format(date, pattern);
	}
	
	/**
	 * 格式化日期
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(Calendar cal, String pattern) {
		return DateFormatUtils.format(cal, pattern);
	}
	
	/**
	 * 格式化日期
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(long l, String pattern) {
		return DateFormatUtils.format(l, pattern);
	}

	public static final String escapeHtml(String input) {
		return StringEscapeUtils.escapeHtml4(input);
	}
	
	public static final String unescapeHtml(String input) {
		return StringEscapeUtils.unescapeHtml4(input);
	}
	
	public static final String escapexml(String input) {
		return StringEscapeUtils.escapeXml(input);
	}
	
	public static final String unescapexml(String input) {
		return StringEscapeUtils.unescapeXml(input);
	}
	
	public static final String jsonCharFilter(String s)
	{
		 StringBuffer sb = new StringBuffer();         
	        for (int i=0; i<s.length(); i++) {   
	            char c = s.charAt(i);     
	             switch (c){   
	             case '\"':         
	                 sb.append("\\\"");         
	                 break;         
	             case '\\':         
	                 sb.append("\\\\");         
	                 break;         
	             case '/':         
	                 sb.append("\\/");         
	                 break;         
	             case '\b':         
	                 sb.append("\\b");         
	                 break;         
	             case '\f':         
	                 sb.append("\\f");         
	                 break;         
	             case '\n':         
	                 sb.append("\\n");         
	                 break;         
	             case '\r':         
	                 sb.append("\\r");         
	                 break;         
	             case '\t':         
	                 sb.append("\\t");         
	                 break;         
	             default:         
	                 sb.append(c);      
	             }   
	         }       
	        return sb.toString();  
	}
	
	/**
	 * 格式化显示文件大小
	 * 
	 * @param size
	 * @return
	 */
	public static String formatFileSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "K";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 获取文件类型所对应的图标
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getIcon(String fileName) {
		String fix = "";
		String fileTypeImg = "unknow.jpg";
		if (fileName.indexOf(".") >= 0) {
			fix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String jpgTypeList = ",unknow,bmp,dll,exe,gif,html,htm,jpg,mid,rar,txt,wav,zip,jsp,";
			String gifTypeList = ",avi,bmp,doc,gif,jpg,mp3,pdf,rar,rm,txt,zip,php,java,xml,class,js,xls,";
			if (gifTypeList.indexOf("," + fix.toLowerCase() + ",") >= 0) {
				fileTypeImg = fix.toLowerCase() + ".gif";
			} else if (jpgTypeList.indexOf("," + fix.toLowerCase() + ",") >= 0) {
				fileTypeImg = fix.toLowerCase() + ".jpg";
			}
		}
		return fileTypeImg;
	}

	/**
	 * 获取文件夹的大小
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public long getFileSize(File f) throws Exception// 取得文件夹大小
	{
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	public static String getFileSuffix(String filename) {
		if (filename != null) {
			if(filename.lastIndexOf(".")==-1){
				return null;
			}else{
				return filename.substring(filename.lastIndexOf(".")+1).toLowerCase();
			}
		} else {
			return null;
		}
	}
	
	/**
	 * 生成上传文件夹路径 格式：yyyyMM/A-Z
	 * 
	 * @return
	 */
	public static String generateFloder() {
		Calendar c = Calendar.getInstance();
		Date d = c.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		Random rd = new Random();
		int m = rd.nextInt(25);// 生成0-25的随机数
		String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		return sdf.format(d) + "/" + s.charAt(m);
	}

	/**
	 * 格式化路径
	 * 
	 * @param path
	 * @return
	 */
	public static String formatFilePath(String path) {
		if (path != null) {
			return path.replace('\\', '/');
		} else {
			return null;
		}
	}

	/**
	 * 获取当天日期
	 * 
	 * @return
	 */
	public static String getCurrentDay() {
		Calendar c = Calendar.getInstance();
		Date d = c.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(d);
	}
	
	/**
	 * 获取当天日期
	 * 
	 * @return
	 */
	public static String getCurrentTime() {
		Calendar c = Calendar.getInstance();
		Date d = c.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(d);
	}

	/**
	 * 压缩文件
	 * @param filePath   c:/upload/a.txt  ---->c:/upload/a.zip
	 * @throws IOException
	 */
	public static void zip(String filePath) throws IOException {
		File file = new File(filePath);
		String fileName=file.getName();
		String path=file.getParentFile().getPath();
		path=formatFilePath(path);
		String newName=path+"/"+fileName.substring(0,fileName.lastIndexOf("."))+".zip";
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newName)));
		ZipEntry zipEntry = new ZipEntry(file.getName());
		zipOutput.putNextEntry(zipEntry);
		int len = 0;
		byte data[] = new byte[1024];
		while ((len = bis.read(data)) != -1) {
			zipOutput.write(data, 0, len);
		}
		bis.close();
		zipOutput.closeEntry();
		zipOutput.close();
		file.delete();
	}
	
	public static void uzip(String zipPath) throws IOException{
		File file = new File(zipPath);
		String path=file.getParent();
		path=formatFilePath(path);
		ZipFile zipFile=new ZipFile(zipPath);
		Enumeration e=zipFile.getEntries();
		ZipEntry zipEntry=null;
		while(e.hasMoreElements()){
			 zipEntry = (ZipEntry) e.nextElement();
			 File f = new File(path+"/"+zipEntry.getName());
             f.createNewFile();
             InputStream in = zipFile.getInputStream(zipEntry);
             FileOutputStream out = new FileOutputStream(f);

             byte[] by = new byte[1024];
             int c;
             while ((c = in.read(by)) != -1) {
                 out.write(by, 0, c);
             }
             out.close();
             in.close();
		}
	}
}
